<?php
namespace app\index\controller;

use Doctrine\Common\Cache\RedisCache;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use Hooklife\ThinkphpWechat\Wechat;
use think\Controller;
use think\Cookie;

class Index extends Controller
{
    public function _initialize()
    {
        $app = Wechat::app();
        $cache = new RedisCache();
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $cache->setRedis($redis);
        $app->access_token->setCache($cache);

        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        $app = Wechat::app();
        $app->access_token;
        $server = $app->server;
        $server->setMessageHandler(function ($message){
            switch ($message->MsgType){
                case 'event':
                    if ($message->Event == 'subscribe'){
                        return '您好！欢迎关注聚凡众拓！';
                    }elseif ($message->Event == 'unsubscribe'){
                        return '您已取消了关注！';
                    }elseif ($message->Event == 'CLICK' && $message->EventKey == '图文消息'){
                        return new News([
                            'title'       => '美女',
                            'description' => '想看吗？',
                            'url'         => 'https://www.baidu.com/',
                            'image'       => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510247367468&di=438997043da5ec1b0867188271b1e5ab&imgtype=0&src=http%3A%2F%2Fwww.5857.com%2Fuploadfile%2F2016%2F0725%2F20160725055407737.jpg',
                        ]);
                    }
                    break;
                case 'text':
                    if ($message->Content == '图文消息'){
                        return new News([
                            'title'       => '美女',
                            'description' => '想看吗？',
                            'url'         => 'https://www.baidu.com/',
                            'image'       => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510247367468&di=438997043da5ec1b0867188271b1e5ab&imgtype=0&src=http%3A%2F%2Fwww.5857.com%2Fuploadfile%2F2016%2F0725%2F20160725055407737.jpg',
                        ]);
                    }else {
                        return new Text(['content' => $message->Content]);
                    }
                    break;
                case 'image':
                    return new Text(['content' => $message->PicUrl]);
                    break;
                case 'voice':
                    return $message->MediaId.'/'.$message->Format.'/'.$message->Recognition;
                    break;
                case 'video':
                    return $message->MediaId.'/'.$message->ThumbMediaId;
                    break;
                case 'location':
                    return $message->Location_x.'/'.$message->Location_Y.'/'.$message->Scale.'/'.$message->Label;
                    break;
                case 'link':
                    return $message->Title.'/'.$message->Description.'/'.$message->url;
                    break;
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $server->serve()->send();
    }

    //群发
    public function mass()
    {
        $app = Wechat::app();
        $broadcast = $app->broadcast;
        $broadcast->sendText("大家好！欢迎使用，聚凡众拓服务号！");
        die('success');
    }

    //群发素材图文消息
    public function sendMaterial()
    {
        $app = Wechat::app();
        $broadcast = $app->broadcast;
        $broadcast->sendNews('XpB8q31qJM-Y-BToaygPjsaSsoOnpCkeNN_3_5uiP6M');
    }

    //模板消息
    public function notice()
    {
        $app = Wechat::app();
        $notice = $app->notice;
        $messageId = $notice->send([
            'touser' => 'o3FY8wcAQgDACJHBboqqbsV-NMk0',
            'template_id' => 'ABFWiMjBoZkNyibdN3Qa-MEmHXykvLiwBi4gjKrvNg8',
            'url' => 'http://overtrue.me',
            'data' => [
                'first' => '我们已收到您的货款，开始为您打包商品，请耐心等待: )',
                'orderMoneySum' => '30.00'.'元',
                'orderProductName' => 'iMac Pro',
                'Remark' => '如有问题请致电400-828-1384或直接在微信留言，小易将第一时间为您服务！',
            ],
        ]);
    }

    //获取用户信息
    public function getUsersInfo()
    {
        $app = Wechat::app();
        $userService = $app->user;
        dump($userService->get('o3FY8wcAQgDACJHBboqqbsV-NMk0'));
    }

    //网页授权
    public function oauth()
    {
        $app = Wechat::app();
        $oauth = $app->oauth;
        if (!Cookie::get('weChat_user')){
            Cookie::set('target_url', 'user/profile');
            return $oauth->redirect();
        }
        dump(Cookie::get('weChat_user'));
    }

    //网页授权回调
    public function oauth_callback()
    {
        $app = Wechat::app();
        $oauth = $app->oauth;
        $user = $oauth->user();
        Cookie::set('weChat_user', $user->toArray(), 3600);
        $targetUrl = Cookie::get('target_url');
        $targetUrl = $targetUrl ? $targetUrl : '/';
        dump($targetUrl);
    }

    //图文消息素材管理
    public function material()
    {
        $app = Wechat::app();
        $material = $app->material;
        $result = $material->lists('news');
        dump($result);
    }

    //添加菜单
    public function addMenus()
    {
        $app = Wechat::app();
        $menu = $app->menu;
        $buttons = [
            [
                "type" => "click",
                "name" => "图文消息",
                "key"  => "图文消息"
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "测试网页授权",
                        "url"  => "http://lxy.zgsh315.com/oauth"
                    ],
                    [
                        "type" => "view",
                        "name" => "视频",
                        "url"  => "http://v.qq.com/"
                    ],
                    [
                        "type" => "click",
                        "name" => "赞一下我们",
                        "key" => "V1001_GOOD"
                    ],
                ],
            ],
        ];
        $menu->add($buttons);
    }

    //查询菜单
    public function getMenus()
    {
        $app = Wechat::app();
        $menu = $app->menu;
        $menus = $menu->all();
        dump($menus);
    }

    //JSSDK使用
    public function jsSdk()
    {
        $app = Wechat::app();
        $js = $app->js;
        return $this->fetch('', [
            'js' => $js
        ]);
    }
}
